<?php

/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

/**
 * Description of My_eventController
 *
 * @author tuancasi
 */
class My_eventController extends Controller {

    public function init() {
	if (user()->isGuest) {
	    $this->redirect(SITE_NAME_URL);
	}
    }

    //put your code here
    public function actionIndex() {
	$criteria = new CDbCriteria();
	$criteria->addCondition('user_id=' . user()->id);
	$criteria->order = 'updated DESC';
	$dataProvider = new CActiveDataProvider('Event', array(
	    'criteria' => $criteria
	));
	$this->render('index', array(
	    'dataProvider' => $dataProvider
	));
    }

    /*
     * 
     */

    public function actionEdit($id) {
	$eventModel = $this->loadModel($id);
	if ($eventModel->user_id == user()->id) {
	    if (isset($_POST['ajax']) && $_POST['ajax'] == "event-form-update") {
		echo CActiveForm::validate($eventModel);
		Yii::app()->end();
	    }
	    if (isset($_POST['update-event'])) {
		unset($_POST['Event']['start']);
		$eventModel->attributes = $_POST['Event'];
		$eventModel->save();
	    }
	    $this->render('edit', array('eventModel' => $eventModel));
	} else {
	    $this->render('edit', array('notOwn' => 1));
	}
    }

    /*
     * 
     * 
     */

    public function actionDelete_event() {
	if (isset($_POST['eventId'])) {
	    $model = $this->loadModel($_POST['eventId']);
	    $model->delete();
	}
    }

    /**
     * Returns the data model based on the primary key given in the GET variable.
     * If the data model is not found, an HTTP exception will be raised.
     * @param integer the ID of the model to be loaded
     */
    public function loadModel($id) {
	$model = Event::model()->findByPk($id);
	if ($model === null)
	    throw new CHttpException(404, 'The requested page does not exist.');
	return $model;
    }

}
